/*
  用法：
    <yl-datetime-picker wx:if="{{ isShow }}" minDate="{{minDate}}" maxDate="{{maxDate}}" defaultDate="{{defaultDate}}" bind:cancel="cancelFunc" bind:confirm="confirmFunc"></yl-datetime-picker>
  Props
    title                 标题
    min-date              最小时间-时间戳 需要x1000
    max-date              最大时间-时间戳 需要x1000
    default-date          默认值-时间戳 需要x1000
    close-click-overlay   是否在点击遮罩层后关闭
    z-index               层级
  Events
    cancel                点击取消
    confirm               点击确定
    click-overlay         点击背景遮罩层触发
  Slot
    无
  外部样式类
    无
*/
Component({
  properties: {
    // 控制显隐
    // isShow: {
    //   type: Boolean,
    //   value: true,
    // },
    // 标题
    title: {
      type: String,
      value: "选择年月日",
    },
    // 最小时间-时间戳 x1000
    minDate: {
      type: Number,
      value: null,
    },
    // 最大时间-时间戳 x1000
    maxDate: {
      type: Number,
      value: null,
    },
    // 默认展示的数据-时间戳 x1000
    defaultDate: {
      type: Number,
      value: Date.parse(new Date()),
      observer: 'updateDefaultDate'
    },
    // 日期格式， day - 年月日， month - 年月， year - 年
    fields: {
      type: String,
      value: "day",
    },
    // 日期类型，现在只支持年月日类型，后期可以扩展时分秒
    mode: {
      type: String,
      value: "date",
    },
    // 是否在点击遮罩层后关闭
    closeClickOverlay: {
      type: Boolean,
      value: true,
    },
    // 层级
    zIndex: {
      type: Number,
      value: 100,
    },
  },
  data: {
    pickerValue: [], // 用于展示默认值
    years: [], // date 类型 年
    months: [], // date 类型 月，从1-12
    days: [], // date 类型 日
    ymd: [], // date 类型 将传递过来的date类型默认值重新获取一下
    minDateArray: [],
    maxDateArray: [],
    defaultDateArray: [],
    dateIsShow: false,
  },
  lifetimes: {
    // 加载成功之后先初始化数据
    attached: function () {
      //  将时间戳转化成内部使用的年月日的数组
      this.data.minDateArray = this.timestampToArray(this.data.minDate);
      this.data.maxDateArray = this.timestampToArray(this.data.maxDate);
      if (this.data.defaultDate) {
        this.data.defaultDateArray = this.timestampToArray(this.data.defaultDate);
      }
      let defaultDateArray = this.data.defaultDateArray;
      this.attachedHandler(defaultDateArray);
    },
    detached: function () {},
  },
  methods: {
    // 更新默认值
    updateDefaultDate(val) {
      if (this.data.defaultDate == 0 || this.data.defaultDate == null) {
        this.data.defaultDate = Date.parse(new Date());
      }
      this.data.defaultDateArray = this.timestampToArray(this.data.defaultDate);
      let defaultDateArray = this.data.defaultDateArray;
      this.attachedHandler(defaultDateArray);
    },
    timestampToArray(date) {
      var date = new Date(date);
      var array = [];
      array.push(date.getFullYear());
      array.push(date.getMonth() + 1);
      array.push(date.getDate());
      return array;
    },
    // 加载成功之后执行
    attachedHandler: function (defaultDateArray) {
      let pickerValue = [];
      let mode = this.data.mode;
      if (mode === "date") {
        if (defaultDateArray.length <= 0) {
          defaultDateArray = [
            new Date().getFullYear(),
            new Date().getMonth() + 1,
            new Date().getDate(),
          ];
        }
        this.setData({
          ymd: defaultDateArray,
        });
        this.initYears();
        return;
      }
      this.setData({
        pickerValue,
      });
    },
    //初始化年份列表
    initYears: function () {
      let fields = this.data.fields;
      let y = this.data.ymd[0];
      let pickerValue = this.data.pickerValue;
      let years = [];
      let yearObj = this.checkYears();
      for (let i = yearObj.start; i >= yearObj.end; i--) {
        years.unshift(i);
      }
      let yearIndex = years.indexOf(y);
      if (yearIndex === -1) {
        yearIndex = years.length - 1;
      }
      pickerValue[0] = yearIndex;
      this.setData({
        years,
        pickerValue,
      });
      if (fields !== "year") {
        this.initMonths(1);
      }
    },
    //初始化月份列表
    initMonths: function (type) {
      let fields = this.data.fields;
      let m = this.fillZero(this.data.ymd[1]);
      let pickerValue = this.data.pickerValue;
      let months = [];
      let monthObj = this.checkMonths();
      for (let i = monthObj.start; i <= monthObj.end; i++) {
        let month = this.fillZero(i);
        months.push(month);
      }
      let monthIndex;
      if (type === 1) {
        monthIndex = months.indexOf(m);
        if (monthIndex === -1) {
          monthIndex = 0;
        }
      } else {
        monthIndex = pickerValue[1];
        if (monthIndex >= months.length) {
          monthIndex = months.length - 1;
        }
      }
      pickerValue[1] = monthIndex;
      this.setData({
        months,
        pickerValue,
      });
      if (fields === "day") {
        this.initDays(type);
      }
    },
    //初始化天数列表 type: 1-初始化， 2-检查
    initDays: function (type) {
      let d = this.fillZero(this.data.ymd[2]);
      let pickerValue = this.data.pickerValue;
      let years = this.data.years;
      let months = this.data.months;
      let days = [];
      let yearIndex = pickerValue[0];
      let monthIndex = pickerValue[1];
      let year, month, dayObj;
      year = years[yearIndex];
      month = months[monthIndex];
      dayObj = this.checkDays(year, month);
      for (let i = dayObj.start; i <= dayObj.end; i++) {
        days.push(this.fillZero(i));
      }
      let dayIndex;
      if (type === 1) {
        // 初始化的时候走这儿
        dayIndex = days.indexOf(d);
        if (dayIndex === -1) {
          dayIndex = 0;
        }
      } else {
        // 后期检查的时候走这儿
        dayIndex = pickerValue[2];
        if (dayIndex >= days.length) {
          dayIndex = days.length - 1;
        }
      }
      pickerValue[2] = dayIndex;
      this.setData({
        days,
        pickerValue,
      });
    },
    // 检查年份
    checkYears: function () {
      let minDateArray = this.data.minDateArray;
      let maxDateArray = this.data.maxDateArray;
      let now = new Date().getFullYear();
      let start, end;
      // 不限制日期
      if (minDateArray[0]) {
        // 如果指定开始日期
        end = minDateArray[0];
      } else {
        // 未指定开始日期
      }
      if (maxDateArray[0]) {
        // 如果指定结束日期
        start = maxDateArray[0];
      } else {
        // 未指定结束日期
      }
      return { start, end };
    },
    // 检查月份
    checkMonths: function () {
      let minDateArray = this.data.minDateArray;
      let maxDateArray = this.data.maxDateArray;
      // let nowFlag = this.data.nowFlag;
      let year = this.data.years[this.data.pickerValue[0]];
      let start = 1,
        end = 12;
      // 不限制日期
      if (minDateArray.length > 0) {
        // 设置了开始时间
        if (year == minDateArray[0]) {
          start = minDateArray[1];
        }
      }
      if (maxDateArray.length > 0) {
        if (year == maxDateArray[0]) {
          end = maxDateArray[1];
        }
      }
      return { start, end };
    },
    // 检查日期：主要检查天，年月不管
    checkDays: function (year, month) {
      let minDateArray = this.data.minDateArray;
      let maxDateArray = this.data.maxDateArray;
      let dayNum;
      switch (Number(month)) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
          dayNum = 31;
          break;
        case 4:
        case 6:
        case 9:
        case 11:
          dayNum = 30;
          break;
        case 2:
          dayNum = 28;
          if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            dayNum = 29;
          }
          break;
        default:
          break;
      }
      let start = 1,
        end = dayNum;
      let startFlag = year == minDateArray[0] && month == minDateArray[1];
      let endFlag = year == maxDateArray[0] && month == maxDateArray[1];
      // 不限制当前日期
      if (minDateArray[2]) {
        if (startFlag) {
          start = minDateArray[2];
        }
      }
      if (maxDateArray[2]) {
        if (endFlag) {
          end = maxDateArray[2];
        }
      }
      return { start, end };
    },

    // 补零
    fillZero: function (num) {
      if (num < 10) {
        return "0" + num;
      } else {
        return "" + num;
      }
    },
    // 空的  不能删除，阻止冒泡使用
    touchBg: function () {},
    // 取消
    cancelFunc: function () {
      // this.setData({
      //   isShow: false,
      // });
      this.triggerEvent("cancel");
    },
    // 确认
    confirmFunc: function () {
      let mode = this.data.mode;
      let pickerValue = this.data.pickerValue;
      let obj = {};
      obj.pickerValue = pickerValue;

      if (mode === "date") {
        let fields = this.data.fields;
        let tmpObj = {};
        tmpObj.year = this.data.years[pickerValue[0]];
        if (fields !== "year") {
          tmpObj.month = Number(this.data.months[pickerValue[1]]);
        }
        if (fields === "day") {
          tmpObj.day = Number(this.data.days[pickerValue[2]]);
        }
        obj.els = tmpObj;
      }
      obj.timestamp = Date.parse(obj.els.year+'/'+obj.els.month+'/'+obj.els.day);
      this.triggerEvent("confirm", obj);
    },
    // 滑动中
    changeFunc: function (e) {
      let value = e.detail.value;
      let fields = this.data.fields;
      this.data.pickerValue = value;
      if (this.data.mode === "date") {
        if (fields !== "year") {
          this.initMonths(2);
        }
        if (fields === "day") {
          this.initDays(2);
        }
      }
    },
    clickOverlay() {
      // 关闭
      this.triggerEvent("clickOverlay", this);
    }
  },
});
